/*
 * @Author: TC 
 * @Date: 2025-05-05 01:40:26 
 * @Last Modified by:   TC 
 * @Last Modified time: 2025-05-05 01:40:26 
 */


import { instantiate, Node, NodePool, Prefab } from "cc";
import { IBaseInterface } from "../../Common/BaseInterface";
import { BasePoolItem } from "../Component/BasePoolItem";

/**
 * 对象池单位
 */
export class PoolUnit extends NodePool implements IBaseInterface {
    private _clone: Prefab | Node = null;

    constructor(clone: Prefab | Node, cnt: number) {
        super();
        this._clone = clone;
        for (let i = 0; i < cnt; i++) {
            const node = instantiate(this._clone) as unknown as Node;
            this.put(node);
        }
    }

    /**
     * 获取一个节点
     * @returns
     */
    public get(): Node {
        let node: Node = null;
        if (this.size() > 0) node = super.get();
        else node = instantiate(this._clone) as Node;
        return node;
    }

    /**
     * 放回一个节点
     * @param node
     */
    public put(node: Node): void {
        const comp = node.getComponent(BasePoolItem);
        if (comp) {
            comp.onPut();
            comp.setPool(this);
        }
        super.put(node);
    }

    /**
     * 清空
     */
    private _clear(): void {
        super.clear();
    }

    /**
     * 获取对象池大小
     * @returns
     */
    public size(): number {
        return super.size();
    }

    release(): void {
        this._clear();
    }
}
